package com.linian.pushforcampus.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.linian.pushforcampus.domain.PushConfigure;
import com.linian.pushforcampus.domain.WechatAccessToken;
import com.linian.pushforcampus.mapper.WeChatAccessTokenMapper;
import com.linian.pushforcampus.service.WechatAccessTokenService;
import com.linian.pushforcampus.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.Configuration;

/**
 * packageName com.linian.pushforcampus.service.Impl
 *
 * @author Lennon
 * @className WechatAccessTokenServiceImpl
 * @date 2023/11/12
 * @description TODO
 */

@Service
@Slf4j
public class WechatAccessTokenServiceImpl implements WechatAccessTokenService {

    @Autowired
    private WeChatAccessTokenMapper weChatAccessTokenMapper;

    @Autowired
    private PushConfigure pushConfigure;

    @Override
    public WechatAccessToken getAllWechatAccessToken() {
        return weChatAccessTokenMapper.getAllWechatAccessToken();
    }

    @Override
    public WechatAccessToken getWechatAccessTokenById(Integer id) {
        return weChatAccessTokenMapper.getWechatAccessTokenById(id);
    }

    @Override
    public void insertWechatAccessToken(WechatAccessToken wechatAccessToken) {
        weChatAccessTokenMapper.insertWechatAccessToken(wechatAccessToken);
    }

    @Override
    public void updateWechatAccessToken(WechatAccessToken wechatAccessToken) {
        weChatAccessTokenMapper.updateWechatAccessToken(wechatAccessToken);
    }

    @Override
    public void deleteWechatAccessTokenById(Integer id) {
        weChatAccessTokenMapper.deleteWechatAccessTokenById(id);
    }

    @Override
    public JSONObject getUserInfo(String code) {

        // 第二步：通过code换取网页授权access_token
        String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + pushConfigure.getAppId() + "&secret=" + pushConfigure.getSecret() + "&code=" + code + "&grant_type=authorization_code";
        log.info("获取token,getTokenUrl=" + getTokenUrl);
        JSONObject getTokenJson = JSONObject.parseObject(HttpUtil.getHttpJsonByUrl(getTokenUrl));
        /*
         * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
         * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
         */
        log.info("获取token,getTokenJson=" + getTokenJson.toJSONString());

        String openid = getTokenJson.getString("openid");
        String access_token = getTokenJson.getString("access_token");
        String refresh_token = getTokenJson.getString("refresh_token");

        // 第五步验证access_token是否失效；展示都不需要
        String vlidTokenUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
        log.info("验证token,vlidTokenUrl=" + vlidTokenUrl);

        JSONObject validTokenJson = JSONObject.parseObject(HttpUtil.getHttpJsonByUrl(vlidTokenUrl));
        log.info("验证token,validTokenJson=" + validTokenJson.toJSONString());
        if (!"0".equals(validTokenJson.getString("errcode"))) {
            // 第三步：刷新access_token（如果需要）-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki，
            String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            log.info("刷新token,refreshTokenUrl=" + refreshTokenUrl);
            JSONObject refreshTokenJson = JSONObject.parseObject(HttpUtil.getHttpJsonByUrl(refreshTokenUrl));
            /*
             * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
             * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
             */
            log.info("刷新token,refreshTokenJson=" + refreshTokenJson.toJSONString());
            access_token = refreshTokenJson.getString("access_token");
        }

        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
        log.info("获取用户信息，getUserInfoUrl=" + getUserInfoUrl.toString());

        JSONObject getUserInfoJson = JSONObject.parseObject(HttpUtil.getHttpJsonByUrl(getUserInfoUrl));
        ;
        /*
         * { "openid":" OPENID", " nickname": NICKNAME, "sex":"1", "province":"PROVINCE"
         * "city":"CITY", "country":"COUNTRY", "headimgurl":
         * "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
         * "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid":
         * "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
         */
        log.info("获取用户信息，getUserInfoJson=" + getUserInfoJson.toString());
        return getUserInfoJson;
    }


}
